package com.crc.luojian.factory.impl;

import com.crc.luojian.annotation.Transactional;
import com.crc.luojian.factory.BeanPostProcessor;
import com.crc.luojian.util.ProxyInstanceUtil;

import java.lang.reflect.Method;

/**
 * @program: luojian-springframework
 * @description:
 * @author: luojian58
 * @create: 2021-06-10 15:36
 */
public class AutoProxyCreator implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        return bean;
    }

    // cglib 创建代理对象
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
        //有事务注解的bean 才
        if(checkHasProxy(bean)) {
            Object proxyBean = new ProxyInstanceUtil().getProxy(bean);
            return proxyBean == null ? bean : proxyBean;
        }else {
            return bean;
        }
    }

    private boolean checkHasProxy(Object bean){
        Class clazz = bean.getClass();
        if(clazz.getAnnotation(Transactional.class) != null){
            return  true;
        }
        Method[] methods = clazz.getMethods();
        if(methods.length>0){
            for (Method method : methods){
                if(method.getAnnotation(Transactional.class)!=null){
                    return true;
                }
            }
        }
        return false;
    }
}
